const Response = require('../utils/response');
const userService = require('../services/userService');

class UserController {
  // 获取用户列表
  async getUserList(req, res) {
    try {
      const users = await userService.getUserList();
      res.json(Response.success(users));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 用户注册
  async register(req, res) {
    try {
      const userId = await userService.register(req.body);
      res.json(Response.success({ id: userId }, '注册成功'));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 用户登录
  async login(req, res) {
    try {
      const { username, password, remember } = req.body;
      const result = await userService.login(username, password, remember);
      
      // 去除敏感信息
      delete result.user.password;
      
      res.json(Response.success({
        token: result.token,
        user: result.user
      }, '登录成功'));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 获取当前用户信息
  async getCurrentUser(req, res) {
    try {
      const user = await userService.getUserById(req.user.id);
      res.json(Response.success(user));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 更新当前用户信息
  async updateUserInfo(req, res) {
    try {
      await userService.updateUser(req.user.id, req.body);
      res.json(Response.success(null, '更新成功'));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 更新密码
  async updatePassword(req, res) {
    try {
      const { oldPassword, newPassword } = req.body;
      await userService.updatePassword(req.user.id, oldPassword, newPassword);
      res.json(Response.success(null, '密码修改成功'));
    } catch (error) {
      if (error.status === 400) {
        res.status(400).json(Response.error(error.message, 400));
      } else {
        res.status(500).json(Response.error(error.message, 500));
      }
    }
  }

  // 获取指定用户信息
  async getUserById(req, res) {
    try {
      const user = await userService.getUserById(req.params.id);
      res.json(Response.success(user));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 获取用户的书籍
  async getUserBooks(req, res) {
    try {
      const books = await userService.getUserBooks(req.params.id);
      res.json(Response.success(books));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }

  // 获取用户的评论
  async getUserComments(req, res) {
    try {
      const comments = await userService.getUserComments(req.params.id);
      res.json(Response.success(comments));
    } catch (error) {
      res.json(Response.error(error.message));
    }
  }
}

module.exports = new UserController(); 